package net.lulihu.pangolin.headless.server.component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;

/**
 * 抽象的网络方法
 */
@Slf4j
public abstract class AbstractNetwork {

    protected ServerBootstrap serverBootstrap;

    /**
     * 绑定端口
     * <p>
     * 如果为0则获取一个当前系统的可用端口
     *
     * @param port 端口
     * @return 真实绑定的本地端口
     */
    public Integer bindPort(Integer port) throws ExecutionException, InterruptedException {
        ChannelFuture channelFuture = serverBootstrap.bind(port);
        channelFuture.get();

        InetSocketAddress socketAddress = (InetSocketAddress) channelFuture.channel().localAddress();
        return socketAddress.getPort();
    }

}
